package com.deercrowing.takeaway.controller.user;

import com.alibaba.fastjson.JSON;
import com.deercrowing.takeaway.common.model.Result;
import com.deercrowing.takeaway.service.OrdersService;
import com.deercrowing.takeaway.vo.OrdersPageVO;
import com.deercrowing.takeaway.vo.OrdersVO;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@Validated
@RestController
@RequestMapping("user/orders")
public class OrdersWithUserController {

    @Autowired
    OrdersService ordersService;

    @GetMapping("/historyOrders")
    public ResponseEntity selectAll(OrdersPageVO ordersPageVO){
        if (ObjectUtils.isEmpty(ordersPageVO)){
            throw new NullPointerException();
        }

        return ResponseEntity.ok(Result.OK(this.ordersService.userOfHistoryOrders(ordersPageVO)));
    }

    @PostMapping("/submit")
    public ResponseEntity submit(@RequestBody OrdersVO ordersVO){
        log.info("订单信息:{}",ordersVO);
        if (ObjectUtils.isEmpty(ordersVO)){
            throw new NullPointerException();
        }

        return ResponseEntity.ok(Result.OK(this.ordersService.orderSubmit(ordersVO)));
    }

    @PutMapping("/payment")
    public ResponseEntity payment(@RequestBody String orderNumber) throws Exception {
        Map<String,String> map = (Map) JSON.parse(orderNumber);
        if (orderNumber == null){
            throw new NullPointerException();
        }
        this.ordersService.paySuccess(map.get("number"));
        return ResponseEntity.ok(Result.OK(this.ordersService.orderPayment(map.get("number"))));
    }

    @GetMapping("/detail/{id}")
    public ResponseEntity orderDetail(@PathVariable @NotNull(message = "主键不能为空") Long id){
        return ResponseEntity.ok(Result.OK(this.ordersService.searchOrderDetailByOrderId(id)));
    }

    @GetMapping("/reminder/{id}")
    public ResponseEntity orderReminder(@PathVariable @NotNull(message = "主键不能为空") Long id){
        this.ordersService.userOfReminder(id);
        return ResponseEntity.ok(Result.OK());
    }

    @PostMapping("repetition/{id}")
    public ResponseEntity orderRepetition(@PathVariable @NotNull(message = "主键不能为空") Long id){
        this.ordersService.userOfRepetition(id);
        return ResponseEntity.ok(Result.OK());
    }

    @PutMapping("/cancel/{id}")
    public ResponseEntity orderCancel(@PathVariable @NotNull(message = "主键不能为空") Long id) throws Exception {
        this.ordersService.userByCancel(id);
        return ResponseEntity.ok(Result.OK());
    }
}
